package org.cheetahworkflow.designer.part;

import java.io.File;
import java.io.IOException;
import java.net.URI;

import org.cheetahworkflow.designer.model.ModuleNode;
import org.eclipse.core.resources.IFile;
import org.eclipse.gef.Request;
import org.eclipse.gef.RequestConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;

public class ModuleNodePart extends LogicNodePart {

	@Override
	public void performRequest(Request req) {
		if (req.getType().equals(RequestConstants.REQ_OPEN)) {
			// dblclick to load the module workflow file
			ModuleNode model = (ModuleNode) getModel();
			String ref = model.getRef();
			if (ref != null && !"".equals(ref)) {
				IWorkbenchPage page = (IWorkbenchPage) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
				IFile currentFile = (IFile) page.getActiveEditor().getEditorInput().getAdapter(IFile.class);
				String currentPath = currentFile.getLocation().toFile().getParent();
				File refFile = new File(currentPath, ref);
				try {
					if (!refFile.exists()) {
						refFile.createNewFile();
					}
					URI refURI = refFile.toURI();
					IDE.openEditor(page, refURI, "org.cheetahworkflow.designer.ui.MultiPageEditor", true);
				} catch (PartInitException e) {
					MessageDialog.openError(null, "Error", "Cannot open reference file.");
				} catch (IOException e) {
					MessageDialog.openError(null, "Error", "Failed to create the reference file.");
				}
			}
		} else {
			super.performRequest(req);
		}
	}
}
